import axios from 'axios'
import { ElMessage } from 'element-plus'

// 根据环境变量设置基础URL
const baseURL = import.meta.env.DEV ? 'http://192.168.1.169:15050/' : '/'

// const baseURL = import.meta.env.DEV ? 'http://192.168.1.169:8033/' : '/'
// 创建axios实例
const $http = axios.create({
  baseURL: baseURL,
  timeout: 5000, // 请求超时时间
})

$http.baseURL = baseURL

// 图片资源URL
const ordUrl = import.meta.env.DEV
  ? 'http://192.168.1.169:8033/ord?file:^metaMain/static/html/metaAuth/static/image/'
  : '/ord?file:^metaMain/static/html/metaAuth/static/image/'

// 请求拦截器
$http.interceptors.request.use(
  (config) => {
    // 判断baseURL可能会改变的情况
    if (config.data && config.data.hasOwnProperty('baseURL')) {
      config.baseURL = config.data.baseURL
      delete config.data.baseURL
    }

    if (config.method === 'post' && config.contentType) {
      config.data = {
        ...config.data, // 让原来的覆盖掉通用的
      }
    }

    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
$http.interceptors.response.use(
  (response) => {
    const res = response.data
    // console.log(res, typeof res)
    if (res && res.responseCommand.toUpperCase() === 'OK') {
      return res
      // return Promise.reject(new Error(res.message || 'Error'))
    } else {
      // debugger
      if (res.requestCommand) {
        ElMessage.error(res.requestCommand)
      }
      return Promise.reject(res)
    }
  },
  (error) => {
    if (error.response && error.response.status === 503) {
      // 隐藏loading遮罩
      const loadingMasks = document.querySelectorAll('.el-loading-mask')
      loadingMasks.forEach((mask) => {
        mask.style.display = 'none'
      })

      // 显示503错误页面
      const existingVue503 = document.getElementById('vue503')
      if (existingVue503) {
        existingVue503.style.display = 'block'
      } else {
        const errorHtml = `
          <div id="vue503" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.9); z-index: 9999; display: flex; align-items: center; justify-content: center;">
            <div class="texta" style="text-align: center;">
              <span class="imgBox" style="display: block; margin-bottom: 20px;">
                <img src="${ordUrl}503.png" alt="503错误" style="width: 100px; height: 100px;" />
              </span>
              <span style="font-size: 18px; color: #666;">
                该功能无授权
              </span>
            </div>
          </div>
        `
        document.body.insertAdjacentHTML('beforeend', errorHtml)
      }
    } else {
      // 隐藏503错误提示
      const vue503Element = document.getElementById('vue503')
      if (vue503Element) {
        vue503Element.style.display = 'none'
      }
      return Promise.reject(error)
    }
  },
)

export default $http
